import os
import requests
from bs4 import BeautifulSoup
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import threading
import re
from datetime import datetime
import json
import webbrowser

#20240302 修复中小学云平台无法下载部分私域课本，即人教版/部编版的部分课本，如果还有问题请及时指出

#20240525 修改目录为本地目录，Windows发行版依然保持原目录
download_directory = os.getcwd()


def close_app():
    root.destroy()

def open_help():
    webbrowser.open_new_tab("https://www.bilibili.com/video/BV1W2421M7pV/")

def open_about():
    webbrowser.open_new_tab("https://yifang.yxxblog.top")

def browse_directory():
    global download_directory
    # 弹出文件选择框让用户选择保存目录
    folder_path = filedialog.askdirectory()
    # 如果用户选择了一个新的目录，那么更新下载目录
    if folder_path != "":
        download_directory = folder_path
    # 清空文本框并插入新的下载目录
    directory_entry.delete(0, tk.END)
    directory_entry.insert(0, download_directory)

def download_book():
    # 获取用户输入的URL
    book_url = url_entry.get()
    if "basic.smartedu.cn" in book_url:  # 判断是否为智慧教育平台下载链接
        download_smartedu_content(book_url)
    else:
        download_pep_content(book_url)

def download_smartedu_content(url):
    content_id_match = re.search(r'contentId=([^&]+)', url)
    if content_id_match:
        content_id = content_id_match.group(1)
        title_url = f"https://s-file-2.ykt.cbern.com.cn/zxx/ndrv2/resources/tch_material/details/{content_id}.json"
        headers={
        'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0'
    }
        response = requests.get(url=title_url,headers=headers)
        json_data = response.text
        title_match = re.search(r'"title"\s*:\s*"([^"]+)"', json_data)
        if title_match:
            title_tag = title_match.group(1)
            if title_tag:
                title = title_tag.strip()  # 获取网页标题并去除两端空格
            else:
                title = None
            if title:
                    sub_directory = title + " " + datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
            else:
                sub_directory = datetime.now().strftime('%Y-%m-%d-%H-%M-%S')

            valid_sub_directory = "".join(c if c.isalnum() or c.isspace() else "_" for c in sub_directory)
            full_path = os.path.join(download_directory, valid_sub_directory)
            os.makedirs(full_path, exist_ok=True)
            download_url = f"https://r2-ndr.ykt.cbern.com.cn/edu_product/esp/assets/{content_id}.pkg/pdf.pdf"
            download_file(download_url, full_path, valid_sub_directory, title)
        else:
            messagebox.showwarning("Warning", "30000")
    
def download_pep_content(url):
    response = requests.get(url)
    response.encoding = response.apparent_encoding
    soup = BeautifulSoup(response.text, 'lxml')
    #创建文件
    title_tag = soup.title
    if title_tag:
        title = title_tag.string.strip()  # 获取网页标题并去除两端空格
    else:
        title = "Untitled"

    valid_title = "".join(c if c.isalnum() or c.isspace() else "_" for c in title)
    full_path = os.path.join(download_directory, valid_title)
    os.makedirs(full_path, exist_ok=True)

    #提取id
    pattern = r"/(\d+)/mobile/index\.html"
    match = re.search(pattern, url)
    if match:
        book_id = match.group(1)
        js_url = "https://book.pep.com.cn/"+book_id+"/mobile/javascript/config.js"
        #提取页面
        js_response = requests.get(js_url)
        if js_response.status_code == 200:
            js_content = js_response.text
            pattern = r"bookConfig\.totalPageCount\s*=\s*(\d+);"
            match = re.search(pattern, js_content)
            if match:
                page_count = match.group(1)
                if int(page_count) > 0:
                    progress_window = tk.Toplevel(root)
                    progress_window.title("下载进度")
                    progress_label = tk.Label(progress_window, text="正在下载...")
                    progress_label.pack(padx=20, pady=10)
                    progress_bar = ttk.Progressbar(progress_window, length=300, mode="determinate", maximum=int(page_count))
                    progress_bar.pack(padx=20, pady=10)
                    def download_pages():
                        for page_number in range(1, int(page_count) + 1):
                            page_url = f"https://book.pep.com.cn/{book_id}/files/mobile/{page_number}.jpg"
                            response = requests.get(page_url)
                            if response.status_code == 200:
                                file_path = os.path.join(full_path, f"{page_number}.jpg")
                                with open(file_path, 'wb') as file:
                                    file.write(response.content)
                                progress_bar["value"] = page_number
                                progress_label.config(text=f"正在下载：{page_number}/{int(page_count)}")
                                progress_window.update()
                                # 添加下载完成的提示
                                if page_number == int(page_count):
                                    progress_label.config(text="下载完成")
                                    messagebox.showinfo("下载完成", f"《{title}》 图片下载完成")
                                    progress_window.destroy()
                    threading.Thread(target=download_pages).start() 
                else:
                    messagebox.showwarning("Warning", "40000")
            else:
                messagebox.showwarning("Warning", "40001")
        else:
            messagebox.showwarning("Warning", "40002")
    else:
        messagebox.showwarning("Warning", "40003")

def download_file(url, directory, filename, title):
    response = requests.get(url)
    if response.status_code == 200:
        file_path = os.path.join(directory, f"{filename}.pdf")
        with open(file_path, 'wb') as file:
            file.write(response.content)
        messagebox.showinfo("下载完成", f"{title}.pdf 下载完成")
    else:
        messagebox.showerror("下载失败", f"{title}.pdf 下载失败")


'''
#单独的放置列
root = tk.Tk()
root.title("电子教材下载器")
root.geometry("460x200")
root.resizable(False, False)

url_label = tk.Label(root, text="请输入电子教材地址：")
url_label.grid(row=0, column=0, sticky='w', padx=5, pady=5)

url_entry = tk.Entry(root, width=50)
url_entry.grid(row=1, column=0, sticky='ew', padx=5, pady=5)

directory_label = tk.Label(root, text="请选择下载目录：")
directory_label.grid(row=2, column=0, sticky='w', padx=5, pady=5)

directory_entry = tk.Entry(root, width=50)
directory_entry.insert(0, download_directory)
directory_entry.grid(row=3, column=0, sticky='ew', padx=5, pady=5)

browse_button = tk.Button(root, text="浏览", command=browse_directory)
browse_button.grid(row=4, column=1, sticky='ew', padx=5, pady=5)

download_button = tk.Button(root, text="下载", command=download_book)
download_button.grid(row=4, column=2, sticky='ew', padx=5, pady=5)
'''

#固定宽度的
root = tk.Tk()
root.title("亿方教材助手 V1.3-0525")
root.geometry("460x200") 
root.resizable(False, False)
url_label = tk.Label(root, text="点击上方文件菜单中选项，复制教材链接后粘贴或直接把支持平台的链接粘贴至下方")
url_label.grid(row=0, column=0, sticky='w', padx=5, pady=5)

url_entry = tk.Entry(root, width=55)
url_entry.grid(row=1, column=0, sticky='ew', padx=5, pady=5)

directory_label = tk.Label(root, text="请选择下载目录：")
directory_label.grid(row=2, column=0, sticky='w', padx=5, pady=5)

directory_entry = tk.Entry(root, width=55)
directory_entry.insert(0, download_directory)
directory_entry.grid(row=3, column=0, sticky='ew', padx=5, pady=5)

button_frame = tk.Frame(root)
#左边的
button_frame.grid(row=4, column=0, sticky='w')
#右边的
# button_frame.grid(row=4, column=0, sticky='e')
#中间的
#button_frame.grid(row=4, column=0)

browse_button = tk.Button(button_frame, text="浏览", command=browse_directory, width=10)
browse_button.pack(side='left', padx=5, pady=5)

download_button = tk.Button(button_frame, text="下载", command=download_book, width=10)
download_button.pack(side='left', padx=5, pady=5)

# 在主窗口中添加菜单栏
menu_bar = tk.Menu(root)
root.config(menu=menu_bar)

# 添加文件菜单
file_menu = tk.Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="文件", menu=file_menu)
file_menu.add_command(label="智教平台教材列表（大部分教材）", command=lambda: webbrowser.open_new_tab("https://basic.smartedu.cn/tchMaterial"))
file_menu.add_command(label="人教社教材列表", command=lambda: webbrowser.open_new_tab("https://jc.pep.com.cn"))
file_menu.add_command(label="关闭", command=close_app)

# 创建学科工具菜单
subject_tools_menu = tk.Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="学科工具", menu=subject_tools_menu)
subject_tools_menu.add_command(label="免费思维导图", command=lambda: webbrowser.open_new_tab("https://mubu.com/home"))
subject_tools_menu.add_command(label="手抄版及幻灯片模板", command=lambda: webbrowser.open_new_tab("https://www.officeplus.cn"))
subject_tools_menu.add_command(label="中小学语文字词表", command=lambda: webbrowser.open_new_tab("https://hanyu.baidu.com/hanyu-page/knowledge/textbook/list"))
subject_tools_menu.add_command(label="古文古诗搜索", command=lambda: webbrowser.open_new_tab("https://www.gushiwen.cn"))
subject_tools_menu.add_command(label="党史及近现代史年表", command=lambda: webbrowser.open_new_tab("https://www.gov.cn/guoqing/lishi.htm"))
subject_tools_menu.add_command(label="人工智能问答", command=lambda: webbrowser.open_new_tab("https://hailuoai.com"))

# 创建排版菜单
formatting_menu = tk.Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="排版及印刷", menu=formatting_menu)

# 添加第一个子菜单项，用于合并多行文本为一行
def merge_lines():
    # 创建一个独立窗口
    merge_window = tk.Toplevel(root)
    merge_window.title("多行文本合并一行")
    merge_window.geometry("400x200")  # 设置窗口大小

    # 创建文本框和按钮
    text_area = tk.Text(merge_window, height=10, width=50)
    text_area.pack(pady=10)
    merge_button = tk.Button(merge_window, text="合并", command=lambda: merge_text(text_area))
    merge_button.pack(pady=10)

def merge_text(text_widget):
    # 获取文本框中的所有文本
    text = text_widget.get("1.0", tk.END)
    # 移除换行符并合并为一行
    merged_text = text.replace("\n", " ")
    # 清空文本框并写入合并后的文本
    text_widget.delete("1.0", tk.END)
    text_widget.insert("1.0", merged_text)

# 添加第二个子菜单项，用于打开网页
def open_rmwatermark():
    webbrowser.open_new_tab("https://www.pdf365.cn/del-watermark")

# 添加子菜单项到排版菜单
formatting_menu.add_command(label="多行文本合并一行", command=merge_lines)
formatting_menu.add_command(label="PDF去水印", command=open_rmwatermark)
# 添加帮助菜单
help_menu = tk.Menu(menu_bar, tearoff=0)
help_menu.add_command(label="使用教程", command=open_help)
help_menu.add_command(label="关于", command=open_about)
menu_bar.add_cascade(label="帮助", menu=help_menu)

root.mainloop()
